#pragma once
#include "Common.h"
#include "ThreadCache.h"
#include "PageCache.h"

static void* MyAlloc(size_t size)
{
	if (size > MAX_BYTES)
	{
		size_t alignSize = CalculateSize::GetBytes(size);
		size_t kpage = alignSize >> 12;

		PageCache::GetInstance()->page_mtx.lock();
		Span* span = PageCache::GetInstance()->NewSpan(kpage);
		span->objSize = size;
		PageCache::GetInstance()->page_mtx.unlock();

		void* ptr = (void*)(span->page << 12);
		return ptr;
	}
	if (tls_ptr == nullptr)
	{
		static ObjectPool<ThreadCache> tcPool;
		tls_ptr = tcPool.New();
	}
	return tls_ptr->Allocate(size);
}
static void MyFree(void* ptr, size_t size)
{
	Span* span = PageCache::GetInstance()->GetObjectToSpan(ptr);
	size_t bytes = span->objSize;

	if (bytes > MAX_BYTES)
	{
		PageCache::GetInstance()->page_mtx.lock();
		PageCache::GetInstance()->ReleaseSpanToPageCache(span);
		PageCache::GetInstance()->page_mtx.unlock();
	}
	else
		tls_ptr->DeAllocate(ptr, size);
}